<template>
  <div class="register-page">
    <h2>注册</h2>
    <form @submit.prevent="onSubmit">
      <input type="text" v-model="username" placeholder="用户名" />
      <input type="email" v-model="email" placeholder="邮箱" />
      <input type="tel" v-model="phone" placeholder="手机号（选填）" />
      <input type="password" v-model="password" placeholder="密码" />
      <input type="password" v-model="confirmPassword" placeholder="确认密码" />
      <div v-if="error" style="color:red;font-size:13px;">{{ error }}</div>
      <button type="submit" :disabled="loading">{{ loading ? '注册中...' : '注册' }}</button>
    </form>
    <div class="login-link">
      已有账号？<router-link to="/login">立即登录</router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useAuth } from '@/composables/auth/useAuth'

const username = ref('')
const email = ref('')
const phone = ref('')
const password = ref('')
const confirmPassword = ref('')
const { register, loading, error } = useAuth()

async function onSubmit() {
  // 表单验证
  if (!username.value || !email.value || !password.value || !confirmPassword.value) {
    error.value = '请填写必填字段'
    return
  }
  
  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email.value)) {
    error.value = '请输入有效的邮箱地址'
    return
  }
  
  // 验证密码长度
  if (password.value.length < 6) {
    error.value = '密码长度不能少于6位'
    return
  }
  
  // 验证两次密码是否一致
  if (password.value !== confirmPassword.value) {
    error.value = '两次输入的密码不一致'
    return
  }
  
  // 调用注册方法
  await register({
    username: username.value,
    email: email.value,
    phone: phone.value || undefined,
    password: password.value
  })
}
</script>

<style scoped>
.register-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 300px;
}

button {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 0;
  cursor: pointer;
  margin-top: 8px;
}

.login-link {
  font-size: 14px;
  text-align: center;
  margin-top: 12px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}
</style>